import { history } from 'ice';
import { Message } from '@alifd/next';
import menuService from '@/services/menu';
import { treeDataTranslate } from '@/utils';

export default {
  state: {
    asideNav: [],
    list: { total: 0, list: [] },
    treeList: [],
    info: {},
  },
  reducers: {
    update: (prevState, payload) => {
      return { ...prevState, ...payload };
    },
  },
  effects: (dispatch) => ({
    fetchAsideNav: async () => {
      const data = await menuService.getNav();
      if (data.code === 0) {
        dispatch.menu.update({ asideNav: data.menuList });
      } else {
        Message.error({
          content: data.msg,
          hasMask: true,
          afterClose: () => {
            history.push('/login');
          },
        });
      }
    },
    fetchList: async () => {
      const data = await menuService.getList();
      const dataList = treeDataTranslate(data, 'menuId', 'parentId');
      return { total: dataList.length, list: dataList };
    },
    treeAuthList: async () => {
      const data = await menuService.getList();
      const dataList = treeDataTranslate(data, 'menuId', 'parentId', 'orderNum', {
        label: 'name',
        value: 'menuId',
        key: 'menuId',
      });
      return { total: dataList.length, list: dataList };
    },
    fetchTreeList: async () => {
      const data = await menuService.getList();
      const dataList = treeDataTranslate(data, 'menuId', 'parentId', 'orderNum', {
        label: 'name',
        value: 'menuId',
        key: 'menuId',
      });
      dispatch.menu.update({ treeList: dataList });
    },
    fetchInfo: async (menuId) => {
      const data = await menuService.getInfo(menuId);
      if (data.code === 0) {
        data.menu.parentId = String(data.menu.parentId);
        if (data.menu.icon === null) {
          data.menu.icon = '';
        }
        if (data.menu.perms === null) {
          data.menu.perms = '';
        }
        if (data.menu.url === null) {
          data.menu.url = '';
        }
        dispatch.menu.update({ info: data.menu });
        return data.menu;
      } else {
        Message.error({
          content: data.msg,
          hasMask: true,
        });
      }
    },
    saveInfo: async (data) => {
      const res = await menuService.saveInfo(data);
      if (res.code === 0) {
        Message.success(res.msg);
      } else {
        Message.error(res.msg);
      }
    },
    updateInfo: async (data) => {
      const res = await menuService.updateInfo(data);
      if (res.code === 0) {
        Message.success(res.msg);
      } else {
        Message.error(res.msg);
      }
    },
    delOne: async (menuId) => {
      const data = await menuService.delOne(menuId);
      if (data.code === 0) {
        Message.success(data.msg);
      } else {
        Message.error(data.msg);
      }
    },
  }),
};
